<template>
    <el-drawer 
        :visible.sync="visible" 
        :title="title"
        direction="rtl"
        size="100%"
        :before-close="handleClose"
        class="md-drawer"
        :wrapper-closable="false"
        ref="mdDrawer">
        <el-form :model="formData" ref="formRef" :rules="rules" label-width="140px" label-position="right">
            <el-form-item prop="type" label="群发类型：">
                <el-select 
                    v-model="formData.type" placeholder="请选择" @change="handleTypeChange">
                    <el-option 
                        v-for="item of actionType" :label="item.name" :value="item.id" :key="item.id">
                    </el-option>
                </el-select>
                <!-- <el-tooltip class="item" effect="light" placement="right-start" style="margin-left: 8px">
                    <template slot="content">
                        <img src="<?php echo SiteUrl ?>/templates/img/msg_type_1.jpg" width="320" v-if="formData.type == 2">
                        <img src="<?php echo SiteUrl ?>/templates/img/msg_type_3.jpg" width="320" v-else>
                    </template>
                  <el-button type="text">查看示例</el-button>
                </el-tooltip> -->
            </el-form-item>
            <el-form-item prop="name" label="群发名称：">
                <el-input v-model="formData.name" maxLength="40" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item required label="选择员工：" class="staff-wrapper">
                <el-form-item prop="send_type" label="">
                    <el-radio-group v-model="formData.send_type" @change="handleRadioChange">
                        <el-radio v-for="item of sendType" :label="item.value" :key="item.value">
                            {{ item.name }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item 
                    prop="sends" label="" v-if="+formData.send_type > 1" class="transfer-wrapper">
                    <div class="transfer-staff">
                        <el-transfer 
                            ref="transferRef"
                            v-model="formData.sends"
                            filterable
                            :data="storeList[formData.send_type]"
                            :props="transferProps"
                            :filter-method="filterMethod"
                            :titles="['源列表', '目的列表']"
                            filter-placeholder="请输入搜索内容"
                            :render-content="transferRenderFunc"
                            @change="handleTransferChange">
                        </el-transfer>
                        <div class="staff-count">预计通知员工数<br><span>{{ formData.sum }}</span>人</div>
                    </div>
                </el-form-item>
            </el-form-item>
            <el-form-item 
                prop="send.content" label="消息内容：" class="form-item__send" v-if="formData.type == 1">
                <el-input 
                    type="textarea" 
                    :rows="6" 
                    placeholder="请输入内容" 
                    v-model="formData.send.content" 
                    maxlength="600" 
                    show-word-limit />
                <div class="send-file-upload__wrapper">
                    <file-upload
                        ref="imageUplodRef"
                        type="image"
                        :multiple="true"
                        :limit="uploadLimit.send.max - uploadLimit.send.uploaded + uploadedList.send.image.length"
                        :show-file-list="false"
                        :file-list="uploadedList.send.image"
                        :oss-upload="true"
                        :on-change="fileList => handleUploadChange('send', 'image', fileList)">
                        <el-button type="text">
                            <svg class="icon svg-icon" :style="`color: ${style.image}`">
                                <use xlink:href="#icon-sop-image"></use>
                            </svg> 图片
                        </el-button> 
                    </file-upload>
                    <file-upload
                        ref="videoUplodRef"
                        type="video"
                        :limit="uploadLimit.send.max - uploadLimit.send.uploaded + uploadedList.send.video.length"
                        :max-size="10"
                        :multiple="true"
                        :show-file-list="false"
                        :file-list="uploadedList.send.video"
                        :oss-upload="true"
                        :on-change="fileList => handleUploadChange('send', 'video', fileList)">
                        <el-button type="text">
                            <svg class="icon svg-icon" :style="`color: ${style.video}`">
                                <use xlink:href="#icon-sop-video"></use>
                            </svg> 视频
                        </el-button> 
                    </file-upload>
                    <file-upload
                        ref="fileUplodRef"
                        :limit="uploadLimit.send.max - uploadLimit.send.uploaded + uploadedList.send.file.length"
                        type="file"
                        :multiple="true"
                        :show-file-list="false"
                        :file-list="uploadedList.send.file"
                        :oss-upload="true"
                        :on-change="fileList => handleUploadChange('send', 'file', fileList)">
                        <el-button type="text">
                            <svg class="icon svg-icon" :style="`color: ${style.file}`">
                                <use xlink:href="#icon-sop-file"></use>
                            </svg> 文件
                        </el-button> 
                    </file-upload>
                    <el-button type="text" @click="handleMsgDialog('send', 'wxs')">
                        <svg class="icon svg-icon" :style="`color: ${style.wxs}`">
                            <use xlink:href="#icon-sop-wxs"></use>
                        </svg> 小程序
                    </el-button>
                    <el-button type="text" @click="handleMsgDialog('send', 'link')">
                        <svg class="icon svg-icon" :style="`color: ${style.link}`">
                            <use xlink:href="#icon-sop-link"></use>
                        </svg> 网页
                    </el-button>
                    <div class="send-uploaded-count">
                        <el-tooltip 
                            class="item" 
                            effect="dark" 
                            :content="`最多支持${uploadLimit.send.max}个附件`" 
                            placement="top">
                            <i class="el-icon-question"></i>
                        </el-tooltip>
                        已选 {{ uploadLimit.send.uploaded }}/{{ uploadLimit.send.max }}
                    </div>
                </div>
                <div class="send-upload-list">
                    <div v-for="(item, index) of Object.entries(uploadedList.send)" :key="index">
                        <div class="send-upload-item" v-for="(item2, index2) of item[1]" :key="index2">
                            <svg class="icon svg-icon" :style="`color: ${style[item[0]]}`">
                                <use :xlink:href="`#icon-sop-${item[0]}`"></use>
                            </svg>
                            <span @click="handleUploadPreview('send', item[0], item2)">
                                {{ item2.file_name || item2.name }}
                            </span>
                            <el-button type="text" @click="handleUploadDel('send', item[0], index2)" size="mini">
                                删除
                            </el-button>
                        </div>
                    </div>
                </div>
            </el-form-item>
            <!-- 此处增加 div 是为了防止 type 切换时执行 resetFields() 方法由于下方第一个el-form-item 未设置 prop 而造成报错 -->
            <div v-else>
                <el-form-item label="消息类型：" required class="form-item__task">
                    <el-form-item prop="task.class" class="form-item__task-class">
                        <el-select size="small" v-model="formData.task.class" @change="handleTaskChange">
                            <el-option 
                                v-for="(item, index) of classType" 
                                :key="index" 
                                :value="item.id" 
                                :label="item.name">
                            </el-option>
                        </el-select>
                        <el-tooltip class="item" effect="light" placement="right-start" v-if="formData.task.class">
                            <template slot="content">
                                <img :src="`/images/task-type-${formData.task.class}.jpg`" width="320" />
                            </template>
                            <el-button type="text" v-if="formData.task.class == ('1' || '2')">查看示例</el-button>
                        </el-tooltip>
                    </el-form-item>
                    <div class="task-template template-text" v-if="formData.task.class == 1">
                        <div class="template-header">
                            插入：
                            <el-button type="text" @click="handleLinkDialog">
                                <svg class="icon svg-icon">
                                    <use xlink:href="#icon-lianjie"></use>
                                </svg>
                                链接
                            </el-button>
                        </div>
                        <div class="template-content">
                            <el-form-item label="" prop="task.text">
                                <el-input 
                                    type="textarea" 
                                    id="task-content" 
                                    class="task-content" 
                                    :rows="5" 
                                    maxlength="600" 
                                    placeholder="示例：您的快递已到，请携带工卡前往邮件中心领取。\n出发前可查看邮件中心视频实况，聪明避开排队。" 
                                    v-model="formData.task.text"
                                    show-word-limit>
                                </el-input>
                            </el-form-item>
                        </div>
                    </div>
                    <div class="task-template template-card" v-else-if="formData.task.class == 2">
                        <el-form-item label="标题" prop="task.title" label-width="50px">
                            <el-input 
                                v-model="formData.task.title" maxlength="30" size="small" placeholder="请输入标题">
                            </el-input> 
                        </el-form-item>
                        <el-form-item label="描述" prop="task.description" label-width="50px">
                            <el-input 
                                v-model="formData.task.description" maxlength="160" size="small" placeholder="请输入描述">
                            </el-input> 
                        </el-form-item>
                        <div class="task-content-title">
                            发送内容： 
                            <el-tooltip class="item" effect="light" placement="right-start">
                                <template slot="content">
                                    <img src="/images/task-type-2-1.jpg" width="320">
                                </template>
                                <el-button type="text">查看示例</el-button>
                            </el-tooltip>
                        </div>
                        <el-form-item label="" prop="task.text">
                            <el-input 
                                type="textarea" :rows="5" maxlength="600" show-word-limit
                                placeholder="请输入内容" v-model="formData.task.text">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="" prop="task.file" class="item-upload-box">
                            <file-upload
                                ref="cardSelectRef"
                                type="image"
                                :limit="uploadLimit.task.max"
                                :multiple="true"
                                :show-file-list="true"
                                list-type="picture-card"
                                :oss-upload="true"
                                :file-list="uploadedList.task.image"
                                :on-change="fileList => handleUploadChange('task', 'image', fileList)"
                                :class="{'hideSelected': uploadLimit.task.max <= uploadLimit.task.uploaded}">
                                <i class="el-icon-plus selected-icon"></i>
                            </file-upload>
                        </el-form-item>
                    </div>
                    <div class="task-template template-card" v-else-if="formData.task.class == 3">
                        <!-- 111 -->
                        <el-form-item label="图片" label-width="65px" style="margin-bottom: 25px;"  prop="task.file" class="item-upload-box">
                            <file-upload
                                ref="cardSelectRef2"
                                key="111"
                                type="image"
                                :limit="1"
                                :multiple="true"
                                :show-file-list="true"
                                list-type="picture-card"
                                :oss-upload="true"
                                :file-list="uploadedList.task.image"
                                :on-change="fileList => handleUploadChange('task', 'image', fileList)"
                                :class="{'hideSelected': uploadLimit.task.max <= uploadLimit.task.uploaded}">
                                <i class="el-icon-plus selected-icon"></i>
                            </file-upload>
                        </el-form-item>

                       <el-form-item label="标题" prop="task.title" label-width="65px">
                            <el-input 
                                v-model="formData.task.title" maxlength="30" size="small" placeholder="请输入标题">
                            </el-input> 
                        </el-form-item>
                        <el-form-item label="描述" prop="task.description" label-width="65px">
                            <el-input 
                                v-model="formData.task.description" type="textarea" :rows="5" maxlength="600" show-word-limit placeholder="请输入描述">
                            </el-input> 
                        </el-form-item>
                        <el-form-item label="链接" prop="task.url" label-width="65px">
                            <el-input 
                                v-model="formData.task.url" maxlength="160" size="small" placeholder="小程序或者url链接必须填写一个">
                            </el-input> 
                        </el-form-item>
                        <el-form-item label="APPID" prop="task.appid" label-width="65px">
                            <el-input 
                                v-model="formData.task.appid" maxlength="160" size="small" placeholder="appid和pageth必须同时填,填写后会忽略链接">
                            </el-input> 
                        </el-form-item>
                        <el-form-item label="页面路径" prop="task.pagepath" label-width="65px">
                            <el-input 
                                v-model="formData.task.pagepath" maxlength="160" size="small" placeholder="appid和pageth必须同时填,填写后会忽略链接">
                            </el-input> 
                        </el-form-item>
                        <!-- 111 -->
                    </div>
                    <div class="task-template template-card" v-else-if="formData.task.class == 4">
                        <!-- 222 -->
                         <el-form-item label="视频文件" label-width="80px" style="margin-bottom: 25px;" prop="task.file" class="item-upload-box">
                            <file-upload
                                ref="cardSelectRef3"
                                class="upload_video"
                                type="video"
                                key="222"
                                :limit="1"
                                :multiple="true"
                                :show-file-list="false"
                                :oss-upload="true"
                                :file-list="uploadedList.task.video"
                                :on-change="fileList => handleUploadChange('task', 'video', fileList)"
                                >
                                <!-- <i class="el-icon-plus selected-icon"></i> -->

                                <el-button  class="upload_video_icon">
                                    <svg class="icon svg-icon " :style="`color: ${style.video}`">
                                        <use xlink:href="#icon-sop-video"></use>
                                    </svg> 上传视频
                                </el-button> 
                            </file-upload>
                            <div class="send-upload-item send-upload-item1" v-if="uploadedList.task.video[0]">
                                <svg class="icon svg-icon" style="color: #60e4b0">
                                    <use xlink:href="#icon-sop-video"></use>
                                </svg>
                                <span @click="handlePreview(uploadedList.task.video[0])">
                                    {{ uploadedList.task.video[0].name }}
                                </span>
                                <el-button type="text" @click="handleDel()" size="mini">
                                    删除
                                </el-button>
                            </div>
                        </el-form-item>

                       <el-form-item label="标题" prop="task.title" label-width="80px">
                            <el-input 
                                v-model="formData.task.title" maxlength="30" size="small" placeholder="请输入标题">
                            </el-input> 
                        </el-form-item>
                        <el-form-item label="描述" prop="task.description" label-width="80px">
                            <el-input 
                                v-model="formData.task.description" type="textarea" :rows="5" maxlength="600" show-word-limit size="small" placeholder="请输入描述">
                            </el-input> 
                        </el-form-item>
                        <!-- 222 -->
                    </div>
                </el-form-item>
            </div>
            <el-form-item prop="trigger_time" label="触达时间：">
                <el-date-picker
                    v-model="formData.trigger_time"
                    type="datetime"
                    format="yyyy-MM-dd HH:mm"
                    value-format="timestamp"
                    placeholder="选择时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item class="button-groups">
                <el-button type="primary" size="small" @click="handleSubmit">确 定</el-button>
                <el-button size="small" @click="handleCancel">取 消</el-button>
            </el-form-item>
        </el-form>
        <!-- 上传dialog -->
        <el-dialog
            :visible.sync="uploadDialogOptions.visible"
            :title="`${uploadDialogOptions.title}配置`"
            custom-class="send__dialog"
            :before-close="handleMsgDialogClose"
            :close-on-click-modal="false"
            append-to-body
            width="600px">
            <el-form 
                :model="uploadDialogData.wxs" 
                :rules="msgTypeWxsRules" 
                ref="msgTypeWxsRef" 
                label-width="136px"
                v-if="uploadDialogOptions.type === 'wxs'">
                <el-form-item label="小程序消息标题：" prop="title">
                    <el-input 
                        size="small" 
                        placeholder="请输入小程序标题" 
                        v-model="uploadDialogData.wxs.title">
                    </el-input>
                </el-form-item>
                <el-form-item label="小程序appId：" prop="appid">
                    <el-select size="small" v-model="uploadDialogData.wxs.appid">
                        <el-option value="wxe863334de4765087" label="元通汽车"></el-option>
                        <el-option value="wxd9c1a2604904086a" label="特选好物购"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="小程序页面路径：" prop="page">
                    <el-input 
                        size="small" 
                        placeholder="请输入小程序页面路径" 
                        v-model="uploadDialogData.wxs.page">
                    </el-input>
                </el-form-item>
                <el-form-item label="小程序消息封面：" prop="cover" ref="coverRef">
                    <file-upload
                        type="image"
                        :limit="uploadLimit.wxs.max"
                        :show-file-list="true"
                        list-type="picture-card"
                        :file-list="uploadDialogData.wxs.cover"
                        :oss-upload="true"
                        :on-change="fileList => handleUploadChange('uploadDialogData', 'wxs', fileList)"
                        :class="{'hideSelected': uploadLimit.wxs.max <= uploadLimit.wxs.uploaded}">
                        <i class="el-icon-plus selected-icon"></i>
                    </file-upload>
                </el-form-item>
            </el-form>
            <el-form 
                :model="uploadDialogData.link" 
                :rules="msgTypeLinkRules" 
                ref="msgTypeLinkRef" 
                label-width="106px" 
                v-else>
                <el-form-item label="链接标题：" prop="title">
                    <el-input 
                        size="small" 
                        placeholder="请输入链接标题" 
                        v-model="uploadDialogData.link.title">
                    </el-input>
                </el-form-item>
                <el-form-item label="链接的描述：" prop="desc">
                    <el-input 
                        size="small" 
                        placeholder="请输入链接描述" 
                        v-model="uploadDialogData.link.desc">
                    </el-input>
                </el-form-item>
                <el-form-item label="链接URL：" prop="page">
                    <el-input 
                        size="small" 
                        placeholder="请输入链接网址" 
                        v-model="uploadDialogData.link.page">
                    </el-input>
                </el-form-item>
                <el-form-item label="链接封面图：" prop="cover" ref="coverRef">
                    <file-upload
                        type="image"
                        :limit="uploadLimit.link.max"
                        :show-file-list="true"
                        list-type="picture-card"
                        :oss-upload="true"
                        :file-list="uploadDialogData.link.cover"
                        :on-change="fileList => handleUploadChange('uploadDialogData', 'link', fileList)"
                        :class="{'hideSelected': uploadLimit.link.max <= uploadLimit.link.uploaded}">
                        <i class="el-icon-plus selected-icon"></i>
                    </file-upload>
                </el-form-item>
            </el-form>
            <template slot="footer" class="dialog-footer">
                <el-button @click="handleMsgDialogClose" size="small">取 消</el-button>
                <el-button type="primary" @click="handleMsgDialogConfirm" size="small">确 定</el-button>
            </template>
        </el-dialog>
        
        <!-- 链接弹框 -->
        <link-dialog :options="linkOptions" @update="handleLinkUpdate"></link-dialog>
        <!-- 预览 -->
        <file-preview ref="filePreviewRef"></file-preview>
    </el-drawer>
</template>
<script>
import { actionType, classType } from '../action_types.js'
import fileUpload from '@/components/home/file-upload.vue'
import linkDialog from '@/components/home/link-dialog.vue'
import filePreview from "@/components/home/file-preview.vue";
export default {
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        data: {
            type: Object,
            default: () => ({})
        }
    },
    components: { fileUpload, linkDialog,filePreview },
    data() {
        return {
            title: '新增群发',
            formData: {
                id: '',                // id
                type: 1,               // 群发类型
                name: '',              // 群发名称
                send_type: '',         // 员工类型
                sends: [],             // 员工列表
                send: {                // 员工群发
                    content: '',       // 消息内容
                    new: []            // 员工群发 附件
                },
                task: {                // 企微任务卡
                    class: "1",        // 消息类型 1 - 文本 2 - 任务卡片
                    title: '',         // 任务卡片 - 标题
                    description: '',   // 任务卡片 - 描述
                    text: '',          // 任务卡片、文本 - 消息内容
                    file: [],           // 任务卡片 附件
                    url: '',   // 图文消息 - 链接
                    appid: '',   // 图文消息 - APPID
                    pagepath: '',   // 图文消息 - 页面路径
                },
                trigger_time: '',      // 触达时间
                sum: 0                 // 预计通知员工数
            },
            rules: {
                type: [{ required: true, message: '请选择类型', trigger: ['blur', 'change'] }],
                name: [{ required: true, message: '请输入名称', trigger: ['blur', 'change'] }],
                send_type: [{ required: true, message: '请选择员工类型', trigger: ['blur', 'change'] }],
                sends: [{ 
                    validator: (rule, value, callback) => {
                        if (!value || value.length <= 0) {
                            return callback(new Error('请选择员工'))
                        } else {
                            return callback()
                        }
                    }, 
                    trigger: ['blur', 'change']
                }],
                "send.content": [{ required: true, message: '请输入内容或上传附件', trigger: ['blur', 'change'] }],
                "task.title": [{ required: true, message: '请输入标题', trigger: ['blur', 'change'] }],
                "task.description": [{ required: true, message: '请输入描述', trigger: ['blur', 'change'] }],
                trigger_time: [{ required: true, message: '请选择触达时间', trigger: ['blur', 'change'] }]
            },
            actionType: actionType(),  // 群发类型
            classType: classType(),    // 企微任务卡类型
            sendType: [
                { name: "全部", value: "1" },
                { name: "品线", value: "2" },
                { name: "单店", value: "3" }
            ],
            transferProps: {
                key: 'id',
                label: 'name',
                disabled: 'disabled'
            },
            storeList: {
                "2": [],               // 品线
                "3": []                // 单店
            },
            uploadLimit: {             // 附件数量限制
                task: {                // 企微任务卡
                    max: 10,           // 最大可上传文件数 
                    uploaded: 0,       // 已上传文件数
                },
                send: {                // 员工群发
                    max: 9, 
                    uploaded: 0
                },
                wxs: {                 // 微信小程序
                    max: 1,            // 封面可上传数
                    uploaded: 0        // 封面已上传数
                },
                link: {                // 网页链接
                    max: 1,            // 封面可上传数
                    uploaded: 0        // 封面已上传数
                }
            },
            style: {
                image: '#6468F1', 
                video: '#1CD88E', 
                file: '#E7B418', 
                wxs: '#03D170', 
                link: '#409EFF'
            },
            uploadedList: {            // 已上传文件
                task: {                // 企微任务卡
                    image: [],
                    video:[],          // 卡片
                },

                send: {                // 员工群发
                    image: [],         // 图片
                    video: [],         // 视频
                    file: [],          // 文件
                    wxs: [],           // 小程序
                    link: []           // 网页链接
                }
            },
            uploadDialogOptions: {     // 小程序、网页链接弹框初始参数
                type: 'wxs', 
                key: '',
                visible: false, 
                title: '小程序', 
                ref: 'msgTypeWxsRef' 
            },
            uploadDialogData: {
                wxs: {                 // 消息小程序配置
                    title: '',         // 小程序标题
                    appid: '',         // 小程序appid
                    page: '',          // 小程序页面路径
                    cover: []          // 小程序封面
                },
                link: {                // 消息网页
                    title: '',         // 链接标题
                    desc: '',          // 链接内容
                    page: '',          // 链接url
                    cover: []          // 链接封面
                }
            },
            msgTypeWxsRules: {
                title: [{ required: true, message: '请输入小程序标题', trigger: ['blur', 'change'] }],
                appid: [{ required: true, message: '请输入小程序appid', trigger: ['blur', 'change'] }],
                page: [{ required: true, message: '请输入小程序页面路径', trigger: ['blur', 'change'] }],
                cover: [{ required: true, message: '请上传小程序封面图', trigger: 'change' }]
            },
            msgTypeLinkRules: {
                title: [{ required: true, message: '请输入链接标题', trigger: ['blur', 'change'] }],
                page: [{ required: true, message: '请输入链接', trigger: ['blur', 'change'] }]
            },
            linkOptions: {             // 插入链接对话框参数
                visible: false
            }
        }
    },
    watch: {
        visible: {
            immediate: false,
            handler(val) {
                if (val) {
                    const { id } = this.data
                    if (id) {
                        this.title = "编辑群发"
                        this.getData()
                    } else {
                        this.title = "新增群发"
                    }
                    this.formData.id = id
                }
            }
        }
    },
    methods: {
        filterMethod(query, item) {
            if (query) {
                return item.name.includes(query)
            } else {
                return item
            }
        },
        handleRadioChange(val) {
            this.formData.sends = []
            this.formData.sum = 0
            this.clearValidate("sends")
            /**
             * 由于el-transfer无重置左侧选中方法，下面采用
             * 让el-transfer组件重新渲染达到重置el-transfer左侧选中数据
             */
            this.formData.send_type = 0
            this.$nextTick(() => this.formData.send_type = val)
        },
        getBlocDepartList() { // 品线列表
            this.$http.post('/admin/marketing/index.php?act=contact&op=blocDepartList').
            then(res => {
                this.storeList['2'] = (res.data || []).map(item => ({
                    id: item.depart_id,
                    name: item.depart_name,
                    count: item.sum
                }))
            }).catch(error => {
                error && this.$message.error(`${error}`)
            })
        },
        getBlocDepartStoreList() { // 单店列表
            this.$http.post('/admin/marketing/index.php?act=contact&op=blocDepartStoreList').
            then(res => {
                this.storeList['3'] = (res.data || []).map(item => ({
                    id: item.store_id,
                    name: item.store_name,
                    count: item.num
                }))
            }).catch(error => {
                error && this.$message.error(`${error}`)
            })
        },
        transferRenderFunc(h, option) {
            if (option.name.length > 9) {
                return <el-tooltip class="item" effect="dark" content={ option.name } placement="top">
                    <span>{ option.name }</span>
                </el-tooltip>
            } else {
                return <span>{ option.name }</span>
            }
        },
        handleTransferChange(stores = []) {
            const { send_type } = this.formData
            const count = this.storeList[send_type].reduce((total, item) => {
                if (stores.includes(item.id)) {
                    total += item.count
                }
                return total
            }, 0)
            this.formData.sum = count
        },
        handleUploadChange(key, subKey, fileList) {
            if (key === 'uploadDialogData') {
                this.uploadDialogData[subKey].cover = fileList
                this.uploadLimit[subKey].uploaded = fileList.length
                this.$refs[this.uploadDialogOptions.ref].validateField(['cover'])
            } else {
                this.uploadedList[key][subKey] = fileList
                let uploaded = 0
                Object.values(this.uploadedList[key]).forEach(item => {
                    uploaded += item.length
                })
                this.uploadLimit[key].uploaded = uploaded
                if (key == 'send' && uploaded > 0) {
                    this.handleRequiredChange('send.content', false)
                }
            }
        },
        handleUploadDel(key, subKey, index) {
            const { id, name } = this.uploadedList[key][subKey][index]
            this.$alert(
                '确定删除'+ name +'吗?', 
                '温馨提示', 
                {
                    type: 'warning',
                    showCancelButton: true
                }
            ).then(() => {
                this.$http.post('/admin/materialLibrary/index.php?act=materialLibrary&op=del', { ids: id }).
                then(res => {
                    if (res.code == 200) {
                        this.uploadedList[key][subKey].splice(index, 1)
                        this.uploadLimit[key].uploaded--
                        if (['wxs', 'link'].includes(subKey)) {
                            this.uploadLimit[subKey].uploaded = 0
                        }
                        if (this.uploadLimit[key].uploaded <= 0) {
                            this.handleRequiredChange('send.content', true)
                        } else {
                            this.handleRequiredChange('send.content', false)
                        }
                        this.$message.success('删除成功')
                    } else {
                        throw '删除失败'
                    }
                }).catch(error => {
                    error && this.$message.error(`${error}`)
                })
            }).catch(error => {})
        },
        handleRequiredChange(key, value = false) {
            this.rules[key][0].required = value
            this.$nextTick(() => {
                if (value) {
                    this.$refs.formRef.validateField([key])
                } else {
                    this.$refs.formRef.clearValidate([key])
                }
            })
        },
        handleUploadPreview(key, subKey, file) {
            if (['wxs', 'link'].includes(subKey)) {
                return this.handleMsgDialog(key, subKey)
            } else {
                this.$refs[`${subKey}UplodRef`].preview(file)
            }
        },
        getData() {
            this.$http.get('/admin/marketing/index.php?act=message&op=info', { params: {id: this.data.id} }).
            then(res => {
                if (res.code == 200) {
                    this.formData = { ...this.formData, ...res.data }
                    this.formData.type = +this.formData.type
                    this.formData.trigger_time = this.formData.trigger_time * 1000
                    this.formData.sends = this.formData.sends ?? []
                    // 统计附件
                    let key = 'send', key2 = 'new'
                    if (res.data.type == 2) {
                        key = "task", key2 = 'file'
                    }
                    let uploaded = 0
                    if (res.data[key][key2]) {
                        res.data[key][key2].forEach(item => {
                            const subKey = item._type || item.type
                            this.uploadedList[key][subKey].push({ ...item })
                            uploaded++
                            if (['wxs', 'link'].includes(subKey)) {
                                this.uploadLimit[subKey].uploaded = item.cover.length
                            }
                        })
                        this.uploadLimit[key].uploaded = uploaded
                        if (uploaded > 0 && key == 'send') {
                            this.handleRequiredChange(key + '.content', false)
                        }
                    }
                }
            })
        },
        handleSubmit() {
            this.$refs.formRef.validate(valid => {
                if (valid) {
                    const datas = { ...this.formData }
                    datas.trigger_time = datas.trigger_time / 1000
                    datas.sends = JSON.stringify(datas.sends)
                    let key = 'send', key2 = 'new'
                    if (datas.type == 2) {
                        key = 'task', key2 = 'file'
                    }
                    datas[key][key2] = []
                    Object.entries(this.uploadedList[key]).forEach(item => {
                        item[1].forEach(file => {
                            datas[key][key2].push({ _type: item[0], ...file })
                        })
                    })
                    datas[key][key2] = JSON.stringify(datas[key][key2])
                    if (key === 'send') delete datas.task
                    else delete datas.send
                    // return
                    this.$http.post("/admin/marketing/index.php?act=message&op=save", datas)
                    .then(res => {
                        if (res.code == 200) {
                            this.$message.success(datas.id ? '编辑成功' : '新增成功')
                            this.handleClose()
                            this.$emit("update")
                        } else {
                            throw res.msg
                        }
                    }).catch(error => {
                        error && this.$message.error(`${error}`)
                    })
                }
            })
        },
        handleClose(done) {
            // if (done) done()
            // this.$refs.formRef.resetFields()
            this.handleTypeChange(1)
            this.$emit("update:visible", false) // 更新父组件visible值
        },
        clearValidate(key = '') {
            this.$nextTick(() => {
                this.$refs.formRef.clearValidate(key)
            })
        },
        handleCancel() {
            this.handleClose()
        },
        // 当上传超过限制钩子
        handleUploadExceed(key) {
            const { max, uploaded } = this.uploadLimit[key]
            this.$message.error('剩余可上传数量为：' + (max - uploaded))
        },
        // 上传前钩子
        handleBeforeUpload(key, subKey = null) {
            if (this.uploadLimit[key].uploaded + 1 > this.uploadLimit[key].max) {
                this.handleUploadExceed(key)
                return false
            }
            return true
        },
        // 小程序、链接对话框
        handleMsgDialog(key, type = 'wxs') {
            const isEdit = this.uploadedList[key][type].length > 0 // > 0 表示已存在，则这里为编辑
            if (!isEdit && !this.handleBeforeUpload(key, type)) {
                return
            }
            this.uploadDialogOptions.type = type
            this.uploadDialogOptions.key = key
            this.uploadDialogOptions.visible = true
            if (type === 'wxs') {
                this.uploadDialogOptions.title = '小程序'
                this.uploadDialogOptions.ref = 'msgTypeWxsRef'
            } else {
                this.uploadDialogOptions.title = '网页'
                this.uploadDialogOptions.ref = 'msgTypeLinkRef'
            }
            if (this.uploadedList[key][type][0]) {
                this.$nextTick(() => {
                    const { cover } = this.uploadedList[key][type][0]
                    this.uploadDialogData[type] = {
                        ...this.uploadedList[key][type][0],
                        cover: [ ...cover ]
                    }
                    this.uploadLimit[type].uploaded = cover.length
                })
            }
            this.$nextTick(
                () => this.$refs[this.uploadDialogOptions.ref].clearValidate()
            )
        },
        handleMsgDialogClose() {
            const { type, key, ref } = this.uploadDialogOptions
            this.$refs[ref].resetFields()
            this.uploadDialogOptions.visible = false
            if (this.uploadedList[key][type].length <= 0) {
                this.uploadLimit[type].uploaded = 0
            }
        },
        handleMsgDialogConfirm() {
            const { title, type, key, ref } = this.uploadDialogOptions
            this.$refs[ref].validate(valid => {
                if (valid) {
                    const data = this.uploadDialogData[type]
                    if (this.uploadedList[key][type].length <= 0) {
                        this.uploadLimit[key].uploaded++
                    }
                    this.uploadedList[key][type] = [{
                        name: `${title}`,
                        ...data
                    }]
                    this.uploadDialogOptions.visible = false
                    this.handleRequiredChange('send.content')
                }
            })
        },
        handleTypeChange(value) {
            // 重置
            this.$refs.formRef.resetFields()
            this.formData.type = value
            Object.entries(this.uploadLimit).forEach(item => {
                item[1].uploaded = 0
            })
            Object.entries(this.uploadedList).forEach(item => {
                Object.entries(item[1]).forEach(_item => {
                    this.uploadedList[item[0]][_item[0]] = []
                })
            })
            Object.entries(this.formData.task).forEach(item => {
                if(item[0] == 'file'){
                    this.formData.task[item[0]] = []
                } else {
                    this.formData.task[item[0]] = ""
                }
                // Object.entries(item[1]).forEach(_item => {
                //     this.uploadedList[item[0]][_item[0]] = []
                // })
            })
            this.formData.task.class = "1"
            if (this.$refs.msgTypeWxsRef) {
                this.$refs.msgTypeWxsRef.resetFields()
            }
            if (this.$refs.msgTypeLinkRef) {
                this.$refs.msgTypeLinkRef.resetFields()
            }
        },
        handleTaskChange(value) {
            this.formData.task = {
                ...this.formData.task,
                text: '',
                title: '',
                description: '',
                file: []
            }
            this.uploadLimit.task.uploaded = 0
            this.uploadedList.task.image = []
            this.uploadedList.task.video = []
            this.$refs.formRef.clearValidate(
                ['title', 'description', 'content', 'file']
            )
        },
        // 打开插入链接对话框
        handleLinkDialog() {
            this.linkOptions = { visible: true, el: 'task-content' }
            const elInput = document.getElementById(this.linkOptions.el)
            const startPos = elInput.selectionStart
            const endPos = elInput.selectionEnd
            if (!this.formData.task.text) this.formData.task.text = ''
            const txt = this.formData.task.text
            if (startPos >= 0 && endPos) {
                this.linkOptions.title = txt.substring(startPos, endPos)
            }
        },
        // 插入链接点击确认
        handleLinkUpdate(val) {
            this.formData.task.text = val
        },
        handlePreview(file) {
            this.$refs.filePreviewRef.preview(file);
        },
        handleDel() {
            this.uploadedList.task.video = []
        }
    },
    created() {
        this.getBlocDepartList()        // 获取品线
        this.getBlocDepartStoreList()   // 获取单店
    }
}
</script>
<style lang="scss" scoped>
.md-drawer {
    height: 100%;
    ::-webkit-scrollbar { 
        width: 10px;
        height: 10px;
    }
    ::-webkit-scrollbar-thumb {
        cursor: pointer;
        background-color: rgba(144, 147, 153, 0.25);
        background-clip: padding-box;
        border-right: 1px solid transparent;
        border-bottom: 1px solid transparent;
        border-radius: 8px;
    }
}
.md-drawer /deep/ {
    .el-drawer {
        max-width: 940px;
    }
    .el-form-item__label {
        padding-right: 6px;
    }
    .staff-wrapper {
        margin-bottom: 0;
        .el-radio__label {
            padding-left: 8px;
        }
    }
    .el-form-item__content > {
        .el-select, .el-input, .transfer-staff, .el-textarea, 
        .send-file-upload__wrapper, .send-upload-list,
        .task-template {
            width: 100%;
            max-width: 562px;
        }
    }
    .transfer-wrapper {
        margin-top: -6px;
    }
    .transfer-staff {
        background-color: #F5F7FA;
        padding: 10px;
        position: relative;
        .staff-count {
            margin-top: 6px;
            font-size: 12px;
            position: absolute;
            left: 209px;
            top: 180px;
            width: 144px;
            text-align: center;
            line-height: 1.6;
            color: #888;
            span {
                font-size: 16px;
                color: #67C23A;
                font-weight: 700;
            }
        }
    }
    .el-transfer-panel__header {
        background-color: #fff;
        .el-checkbox__label {
            font-size: 13px;
        }
    }
    .el-transfer__buttons {
        padding: 0 20px;
    }
    .el-form-item.is-error .el-transfer .el-input__inner {
        border-color: #EBEEF5;
    }
    // 员工群发
    .form-item__send .el-textarea__inner {
        border-radius: 3px 3px 0 0;
    }
    .send-file-upload__wrapper {
        box-sizing: border-box;
        height: 37px;
        padding: 0 10px 1px;
        box-sizing: border-box;
        border: 1px solid var(--base-border-color-deep-1);
        border-top-width: 0;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        position: relative;
        z-index: 0;
        border-radius: 0 0 3px 3px;
        line-height: 100%;
        border: 1px solid #DCDFE6;
        border-top: 0;
        .file-upload__selected {
            height: 20px;
        }
        .el-button {
            font-size: 13px;
            margin-left: 0;
            margin-right: 20px;
            padding: 0;
            height: 20px;
            overflow: hidden;
            color: #333;
            display: flex;
            align-items: center;
            &:hover {
                opacity: .7;
            }
            span {
                display: flex;
                align-items: center;
            }
        }
        .svg-icon {
            width: 18px;
            height: 18px;
            margin: 0 5px 0 0;
        }
    }
    .send-uploaded-count {
        position: absolute;
        right: 10px;
        display: flex;
        align-items: center;
        color: #999;
        margin-top: -2px;
        font-size: 13px;
        i {
            font-size: 16px;
            color: rgba(120, 120, 120, .6);
            margin: 1px 3px 0 0;
        }
    }
    .send-upload-item {
        background-color: #ECF5FF;
        display: flex;
        align-items: center;
        height: 34px;
        margin: 6px 0;
        position: relative;
        font-size: 12px;
        border-radius: 3px;
        &:last-child {
            margin-bottom: 0;
        }
        .svg-icon {
            width: 18px;
            height: 18px;
            margin: 0 6px 0 12px;
        }
        > span {
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
            display: inline-block;
            max-width: calc(100% - 100px);
            line-height: 14px;
            height: 16px;
            cursor: pointer;
            &:hover {
                color: #409EFF;
            }
        }
        .el-button {
            position: absolute;
            right: 12px;
            color: #409EFF;
        }
    }
    // 企微任务卡
    .form-item__task {
        &.el-form-item {
            margin-bottom: 0;
        }
        .form-item__task-class {
            .el-select {
                margin-right: 8px;
            }
        }
        .task-template {
            &.template-text {
                .template-header {
                    border: 1px solid #DCDFE6;
                    border-bottom: 0;
                    background-color: #F5F7FA;
                    height: 32px;
                    line-height: 32px;
                    border-radius: 4px 4px 0 0;
                    padding: 0 15px;
                    box-sizing: border-box;
                    .el-button { 
                        padding: 0px 2px; 
                        color: #409EFF;
                    }
                    .svg-icon {
                        width: 14px;
                        height: 14px;
                        fill: #409EFF;
                        vertical-align: -2px;
                    }
                }
                .task-content.el-textarea {
                    .el-textarea__inner { 
                        border-radius: 0 0 3px 3px;
                    }
                }
            }
            .el-input, .el-textarea {
                max-width: 100%;
                min-width: auto;
            }
            &.template-card {
                background-color: #F5F7FA;
                border: 1px solid #DCDFE6;
                border-radius: 3px;
                padding: 12px 12px 6px;
                box-sizing: border-box;
                margin-bottom: 18px;
                .task-content-title {
                    margin-top: -10px;
                    padding-bottom: 2px;
                    color: #666;
                    &::before {
                        content: '*';
                        color: #F56C6C;
                    }
                }
                .file-upload-wrapper {
                    width: calc(100% + 12px);
                }
                .file-upload__selected.item-picture-card,
                .file-upload-list__item.item-picture-card {
                    width: 99px;
                    height: 99px;
                    overflow: hidden;
                }
                .item-upload-box {
                    margin-bottom: 0;
                }
                // .el-form-item__label {
                //     // text-align: right;
                // }
            }
        }
    }
}
// 小程序、网页dialog
.send__dialog .el-input, 
.send__dialog .el-select, 
.send__dialog .el-textarea {
    width: 400px;
}
/deep/.send__dialog .el-form-item__label {
    padding-right: 5px;
}
.file-upload-wrapper.hideSelected /deep/.file-upload__selected {
    display: none;
}
.upload_video /deep/.el-upload {
    text-align: left;
}       
.upload_video_icon{
    font-size: 12px;
}
</style>